package org.web2024.service.serviceimp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.web2024.dao.User;
import org.web2024.dao.UserdetailsImp;
import org.web2024.mapper.UserMapper;

import java.util.Objects;

   @Component
   public class UserdetailsServiceImp implements UserDetailsService {
       @Autowired
       private UserMapper userMapper;

       @Value("${superadimin.username}")
       private String superAdminName;
       @Value("${superadimin.password}")
       private String superAdminPassword;

       @Override
       public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
           if (superAdminName.equals(username)) {

               User superAdmin = new User(1,superAdminName, superAdminPassword);
               return new UserdetailsImp(superAdmin);
           }
           try {
               User user = userMapper.getUserInfo(username);
               if (Objects.isNull(user)) {
                   throw new UsernameNotFoundException("用户不存在");
               }
               return new UserdetailsImp(user);
           } catch (NumberFormatException e) {
               throw new UsernameNotFoundException("用户名格式错误");
           }
       }
   }

